<template>
    <div class="search">
        <div class="operate">
            <el-dropdown @command="export_message">
                <el-button icon="el-icon-share" circle size="small"></el-button>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="txt">txt</el-dropdown-item>
                    <el-dropdown-item command="word">word</el-dropdown-item>
                    <el-dropdown-item command="excel">excel</el-dropdown-item>
                    <el-dropdown-item command="markdown">markdown</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            <el-button icon="el-icon-brush" circle size="small" @click="reset"></el-button>
            <el-button v-for="item in tags" :key="item.id" round size="small" @click="handleTagClick(item)">
                {{ item.name }} </el-button>
        </div>
        <div class="messages-box">
            <i class="el-icon-paperclip ico-upload" @click="fileFormVisible = true"></i>
            <el-input ref="messageInput" type="textarea" clearable autosize v-model="messages" placeholder="输入内容" @keydown.native="handleKeydown"></el-input>
            <div v-if="messages.length > 0" @click="submit" class="btn-send btn-blue-send">
                <i class="el-icon-s-promotion"></i>
            </div>
            <div v-else class="btn-send btn-gray-send">
                <i class="el-icon-s-promotion"></i>
            </div>
        </div>
        <el-dialog ref="dialog" title="文件上传" :visible.sync="fileFormVisible" :modal-append-to-body='false'>
            <File />
        </el-dialog>
    </div>
</template>

<script>
import { del_message, get_tags } from "@/apis/message";
import { update_msg } from "@/apis/group";
import File from "@/views/message/components/File";
import setting from '@/setting'

export default {
    components: { File },
    comments: [File],
    name: "SendMessage",
    data() {
        return {
            fileFormVisible: false,
            group: '',
            messages: '',
            isSubmitting: false, // 添加一个标志位来跟踪是否正在提交
            url: setting.BaseUrl + 'send/',
            form: {
                messages: [],
                type: 'user',
                stream: true,
                group: ''
            },
            ai_form: {
                messages: "",
                type: 'assistant',
                model: 1,
                group: 6
            },
            tags: [],
        }
    },
    beforeMount() {
        this.bus.$on("group", group => {
            this.group = group;
            this.form.group = group.id;
            this.restoreConversationState(group.id);
        });
        this.bus.$on("tags", tags => {
            this.tags = tags;
        });
    },
    mounted() {
        this.$refs.dialog.rendered = true
    },
    methods: {
        async submit() {
            if (this.isSubmitting) {
                return; // 如果正在提交，则直接返回，防止重复提交
            }
            var cur_group = this.group['id'];
            let messages = JSON.parse(localStorage.getItem('message')) || [];
            messages.push({ "role": "user", "content": this.messages });
            this.messages = '';
            this.bus.$emit("toList", messages);
            this.form.messages = messages;
            messages.push({ "role": "assistant", "content": '' });
            let bus = this.bus;

            const abortController = new AbortController();
            const signal = abortController.signal;

            const displayData = (data) => {
                console.log(data);
                messages[messages.length - 1]["content"] += data;
                console.log(messages);
            }

            this.isSubmitting = true; // 开始提交时设置标志位
            this.bus.$emit('lod', this.isSubmitting);
            this.bus.$emit('lockLists', true); // 锁定对话列表和应用列表

            try {
                const response = await fetch(this.url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + (window.localStorage.getItem('token') || '')
                    },
                    body: JSON.stringify(this.form),
                    signal: signal // 将 signal 传递给 fetch 请求
                });

                if (!response.ok) {
                    throw new Error('Response failed');
                }

                const reader = response.body.getReader();

                const read = async () => {
                    const result = await reader.read();
                    if (signal.aborted) {
                        return;
                    }
                    if (!result.done) {
                        var value = result.value;
                        var decoder = new TextDecoder('utf-8');
                        var chunk = decoder.decode(value);
                        displayData(chunk);
                        bus.$emit("toList", messages);
                        if (cur_group !== this.group['id']) {
                            abortController.abort();
                            // 不清除消息列表，只中断读取
                            this.isSubmitting = false;
                            this.bus.$emit('lod', this.isSubmitting);
                            this.bus.$emit('lockLists', false); // 解锁对话列表和应用列表
                            return;
                        }
                        return read();
                    }
                };

                await read();
            } catch (error) {
                if (signal.aborted) {
                    return;
                }
                alert("智能助手发生异常，请与管理员联系。");
                this.$message({
                    type: 'error',
                    message: 'error'
                });
                console.log(error);
            } finally {
                if (cur_group === this.group['id']) {
                    this.isSubmitting = false; // 提交完成后清除标志位
                    this.bus.$emit('lod', this.isSubmitting);
                    localStorage.setItem('message', JSON.stringify(messages));
                    update_msg({ id: this.group.id, msg: JSON.stringify(messages) });
                } else {
                    this.isSubmitting = false; // 提交完成后清除标志位
                    this.bus.$emit('lod', this.isSubmitting);
                }
                this.bus.$emit('lockLists', false); // 解锁对话列表和应用列表
            }
        },

        reset() {
            update_msg({ id: this.group.id, msg: "[]" })
            localStorage.setItem('message', "[]")
            this.bus.$emit("toList", []);
        },

        export_message(cmd) {
            console.log(cmd.toString())
            this.bus.$emit("exports", cmd.toString())
        },
        handleTagClick(item) {
            this.messages += item.prompt + '\n';
            this.$nextTick(() => {
                this.$refs.messageInput.focus();
            });
        },
        handleKeydown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                if (this.messages.trim() !== '') {
                    this.submit();
                }
            } else if (event.key === 'Enter' && event.shiftKey) {
                event.preventDefault();
                this.messages += '\n';
            }
        }
    }


}
</script>



<style scoped>
.search {
    margin: auto;
    padding: 10px;
}

.messages-box {
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    position: relative;
    overflow: hidden;
    padding-top: 18px;
    padding-bottom: 18px;
    padding-left: 18px;
    margin: 10px auto;
    display: flex;
}

:deep(.el-textarea__inner) {
    border: none;
    padding-right: 45px;
    resize: none;
    overflow-y: auto;
    box-sizing: border-box;
    max-height: 150px
}

.ico-upload {
    font-size: 25px;
    cursor: pointer;
}

.btn-send {
    position: absolute;
    right: 16px;
    bottom: 12px;
    width: 32px;
    height: 32px;
    line-height: 32px;
    border-radius: 8px;
    text-align: center;
}

.btn-blue-send {
    background-color: #487fff;
}

.btn-gray-send {
    background-color: #E5E5E5;
}

.btn-send i {
    font-size: 18px;
    color: #fff;
}

.operate {
    margin-bottom: 10px;
}

:deep(.el-icon-brush) {
    transform: rotate(180deg);
    font-size: 15px;
}
</style>